#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2018, Niklas Hauser
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

def get_properties(env):
    device = env[":target"]
    driver = device.get_driver("usart:stm32*")
    properties = {
        "target": device.identifier,
        "driver": driver,
        "over8_sampling": ("feature" in driver) and ("over8" in driver["feature"]),
        "use_fiber": env.get(":processing:protothread:use_fiber", True)
    }
    return properties

class Instance(Module):
    def __init__(self, instance, is_extended = False):
        self.instance = instance
        self.is_extended = is_extended

    def init(self, module):
        module.name = str(self.instance)
        module.description = "Instance {}".format(self.instance)

    def prepare(self, module, options):
        module.depends(":platform:uart:{}".format(self.instance))
        return True

    def build(self, env):
        properties = get_properties(env)
        properties["id"] = self.instance
        properties["extended"] = self.is_extended

        env.substitutions = properties
        env.outbasepath = "modm/src/modm/platform/spi"

        env.template("uart_spi_master.hpp.in", "uart_spi_master_{}.hpp".format(self.instance))
        env.template("uart_spi_master.cpp.in", "uart_spi_master_{}.cpp".format(self.instance))

def init(module):
    module.name = ":platform:uart.spi"
    module.description = "USART in SPI Mode"

def prepare(module, options):
    device = options[":target"]
    if not device.has_driver("usart:stm32") and not device.has_driver("usart:stm32-extended"):
        return False

    module.depends(
        ":architecture:spi",
        ":cmsis:device",
        ":platform:gpio",
        ":platform:uart")

    if device.get_driver("usart:stm32-extended"):
        for instance in device.get_driver("usart:stm32-extended")["instance"]:
            module.add_submodule(Instance(int(instance), True))

    if device.get_driver("usart:stm32"):
        for instance in device.get_driver("usart:stm32")["instance"]:
            module.add_submodule(Instance(int(instance)))

    return True

def build(env):
    pass
